<template>
  <div class="slider-container">
    <div class="slider-bg" :class="{ 'slider-success': isVerified }">
      <div class="slider-text">{{ isVerified ? '验证通过' : '向右滑动验证' }}</div>
      <div
        class="slider-button"
        :style="{ left: `${position}px` }"
        @mousedown="handleMouseDown"
        :class="{ 'slider-button-success': isVerified }"
      >
        <el-icon><ArrowRight /></el-icon>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ArrowRight } from '@element-plus/icons-vue';

const props = defineProps<{
  onSuccess?: () => void;
}>();

const position = ref(0);
const isVerified = ref(false);
const startX = ref(0);
const isDragging = ref(false);

const handleMouseDown = (e: MouseEvent) => {
  if (isVerified.value) return;
  isDragging.value = true;
  startX.value = e.clientX - position.value;

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};

const handleMouseMove = (e: MouseEvent) => {
  if (!isDragging.value) return;

  const newPosition = e.clientX - startX.value;
  const maxPosition = 320; // 滑块容器宽度 - 滑块宽度

  position.value = Math.max(0, Math.min(newPosition, maxPosition));

  if (position.value >= maxPosition - 5) {
    isVerified.value = true;
    position.value = maxPosition;
    props.onSuccess?.();
    handleMouseUp();
  }
};

const handleMouseUp = () => {
  if (!isVerified.value) {
    position.value = 0;
  }
  isDragging.value = false;
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
};
</script>

<style scoped>
.slider-container {
  width: 100%;
  height: 40px;
  margin-bottom: 20px;
}

.slider-bg {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: background-color 0.3s;
}

.slider-success {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.slider-text {
  position: absolute;
  width: 100%;
  height: 100%;
  line-height: 40px;
  text-align: center;
  color: #909399;
  user-select: none;
}

.slider-button {
  position: absolute;
  top: 0;
  width: 40px;
  height: 38px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;
}

.slider-button:hover {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

.slider-button-success {
  background-color: #67c23a;
  border-color: #67c23a;
  color: #fff;
}
</style>